package elitech.vietnam.weatherfashion.notification;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import elitech.vietnam.weatherfashion.R;

public class NotificationEndlessListView extends ListView implements OnScrollListener {

	private View loading_footer;
	private View end_footer;
	private boolean isLoading;
	private boolean isEnded = false;
	private EndlessListener listener;

	public NotificationEndlessListView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);	
		this.setOnScrollListener(this);
	}

	public NotificationEndlessListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.setOnScrollListener(this);
	}

	public NotificationEndlessListView(Context context) {
		super(context);		
		this.setOnScrollListener(this);
	}

	public void setListener(EndlessListener listener) {
		this.listener = listener;
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {

		if (isEnded)
			return;
		
		if (getAdapter() == null)
			return ;

		if (getAdapter().getCount() == 0)
			return ;

		int l = visibleItemCount + firstVisibleItem;
		if (l >= totalItemCount && !isLoading && !isEnded) {
			// It is time to add new data. We call the listener
			listener.loadData();
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {}

	public void setLoadingView(int resId) {
		LayoutInflater inflater = (LayoutInflater) super.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		loading_footer = (View) inflater.inflate(resId, null);
	}
	
	public void setEndView(int resId) {
		LayoutInflater inflater = (LayoutInflater) super.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		end_footer = (View) inflater.inflate(resId, null);
	}

	public EndlessListener setListener() {
		return listener;
	}

	public static interface EndlessListener {
		public void loadData() ;
	}

	public void endOfList() {
		isEnded = true;
		if (end_footer == null)
			setEndView(R.layout.layout_endlist);
		this.addFooterView(end_footer);
	}
	
	public void loadMore(boolean state) {
		isLoading = state;
		if (loading_footer == null)
			setLoadingView(R.layout.layout_loadmore);
		if (state) 
			addFooterView(loading_footer);
		else
			removeFooterView(loading_footer);
	}
}
